<template>
  <el-drawer :model-value="drawerVisible" direction="rtl" @close="closeDrawer">
    <template #header>
      <h4>分配权限</h4>
    </template>
    <template #default>
      <el-tree
        style="max-width: 600px"
        :data="permissionList"
        show-checkbox
        default-expand-all
        node-key="id"
        :props="defaultProps"
        ref="treeRef"
      />
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="cancelClick">取消</el-button>
        <el-button type="primary" @click="confirmClick">确定</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { nextTick, ref, watch } from "vue";
import {
  reqAssignPermission,
  reqGetPermissionById,
  reqGetPermissionList,
} from "../../../api/acl/menu";
import { ElMessage } from "element-plus";
import { objectToQueryString } from "../../../utils/toQueryParam";

const emit = defineEmits(["close"]);
const permissionList = ref([]);
const rolePermission = ref([]);
const selectedList = ref([]);
const permissionId = ref([]);
const treeRef = ref();

const props = defineProps({
  drawerVisible: {
    type: Boolean,
    default: false,
  },
  drawerType: {
    type: Number,
    default: 0,
  },
  roleId: {
    type: Number,
  },
});
const defaultProps = {
  children: "children",
  label: "name",
};
watch(
  () => props.drawerVisible,
  async () => {
    getPermissionList();
    nextTick(async () => {
      let result = await reqGetPermissionById(props.roleId);
      rolePermission.value = result.data;
      selectedList.value = [];
      dfs(rolePermission.value);
      // console.log(rolePermission.value);
      // console.log(selectedList.value);
      treeRef.value.setCheckedKeys(selectedList.value, false);
      console.log(treeRef.value.getCheckedNodes(false, false));
    });
  }
);
const cancelClick = () => {
  emit("close");
};
const confirmClick = async () => {
  permissionId.value = [];
  treeRef.value.getCheckedNodes(false, false).forEach((item: any) => {
    permissionId.value.push(item.id);
  });
  const queryParam = objectToQueryString({
    roleId: props.roleId,
    permissionId: permissionId.value,
  });

  let result = await reqAssignPermission(queryParam);
  if (result.code === 200) {
    ElMessage.success("分配成功");
    emit("close");
    
  } else {
    ElMessage.error("分配失败");
    emit("close");
  }
};
const closeDrawer = () => {
  emit("close");
};
const getPermissionList = async () => {
  let result = await reqGetPermissionList();
  permissionList.value = result.data;
};

function dfs(tree: any) {
  tree.forEach((item: any) => {
    if (item.children.length > 0) {
      dfs(item.children);
    } else {
      if (item.select) {
        selectedList.value.push(item.id);
      }
    }
  });
}
</script>

<style lang="scss" scoped></style>
